'''
Created on 23.2.2011.

@author: Ana Banana
'''

import sys
import re
from loading.xmlparser.network import Network
from loading.xmlparser import XMLParser

class Runner:
    """
    Runs the program, starts the loading of the PPI networks in xml
    format and stores them in gml format
    """
    #the location of the config file should be set relatively
    
    def parseConfigFile (self):
        config_file = r"../../../config/config.txt";
        file = open (config_file, "r");
        lines = file.readlines();
        files = [] #list of files to be parsed
        for line in lines:
            if re.match("^#", line):
                continue;
            elif len(line) <= 1:    #avoid the line feed
                continue;
            else:
                file_being = re.split("\t", line);
                files.append(file_being[0]);
        
        return files
    
    def writeGMLFiles (self, file, writingDirectory):
        file_names = file.split('\\');
        file_name = file_names[len(file_names)-1].split('.')[0];
        file_name = writingDirectory + file_name + ".gml"
        print file_name
        net = Network.Network('Scere')
        xl = XMLParser.XMLoader(file, net)
        xl.loadFile(file);
        xl.handlePPI()
        
        nodes = xl.net.nodes
        edges = xl.net.edges
        
        file = open (file_name, 'w');
        file.write ("graph [\n")
        print len(nodes)
        for k,n in nodes.items():
            file.write ('\tnode [\n');
            file.write ('\t\tid %s\n' % (n.id));
            file.write ('\t\tshort_label \"%s\"\n' % (n.getShortLabel()));
            file.write ('\t\tfullName \"%s\"\n' % (n.getFullName()));
            #file.write ('\t\tentrez_id %s\n' % (n.getIdEntrez()));
            file.write ('\t\tuniprot_id \"%s\"\n' % (n.getIdUniprot()));
            file.write ('\t\tncbiTaxId \"%s\"\n' % (n.getNcbiTaxId()));
            file.write ('\t]\n')
        for e in edges:
            file.write ('\tedge [\n');
            file.write ('\t\tsource %s\n' % (e.getNode1(nodes).getId()));
            file.write ('\t\ttarget %s\n' % (e.getNode2(nodes).getId()));
            #file.write ('\t\tuid %s\n' % (e.uid));
            file.write ('\t]\n')
        file.write (']')
                
                

r = Runner();
if len(sys.argv) == 1:
    print "Potrebno je predati put do direktorija za spremanje gml datoteka pri pokretanju programa.\n";
    exit(-1);
files = r.parseConfigFile();
writingDirectory = sys.argv[1];
for file in files:
    r.writeGMLFiles(file , writingDirectory)
        
    
